import {
	login,
	logout,
	getInfo,
	queryAdminApi,
} from '@/api/login'
import {
	getToken,
	setToken,
	removeToken,
	removeUserId
} from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'

const useUserStore = defineStore('user', {
	state: () => ({
		token: getToken(),
		// 用户Id
		userId: '',
		// 用户名
		name: '',
		// 头像
		avatar: '',
		// 邮箱
		email: '',
		// 手机
		phone: '',
		// 性别
		sex: '1',
		// 当前用户是否是管理员
		isAdmin: false,
		
		// 所属机构id
		orgId: '',
		// 所属机构名称
		orgName: '',
		
		// 部门等级
		deptLevel: '',
		// 部门列表
		depts: [],
		// 角色
		roles: [],
		// 权限
		permissions: [],
		// 省Id
		provinceId:'',
	}),
	// getters: {},
	actions: {
		// 登录
		login(userInfo) {
			const username = userInfo.username.trim()
			const password = userInfo.password
			const code = userInfo.code
			const uuid = userInfo.uuid
			return new Promise((resolve, reject) => {
				login(username, password, code, uuid).then(res => {
					setToken(res.token)
					this.token = res.token
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 获取用户信息
		getInfo(userId) {
			return new Promise((resolve, reject) => {
				getInfo(userId).then(res => {
					const user = res.user
					// 头像
					const avatar = (user.avatar == "" || user.avatar == null) ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;
					this.avatar = avatar;
					// 用户信息
					if(user) {
						this.userId = user.userId||'';
						this.name = user.userName||'';
						this.email = user.email||'';
						this.phone = user.mobilePhone||'';
						this.sex = user.sex||'1';
						this.orgId = user.orgId||'';
						this.orgName = user.orgName||'';
						this.deptLevel = user.deptLevel||'';
						this.depts = user.depts||[];
						this.provinceId = user.provinceId||'';
						// 缓存
						localStorage.setItem("userName", user.userName);
						localStorage.setItem("orgName", user.extend10 || user.orgName);
					}
					// 角色
					if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
						this.roles = res.roles;
						this.permissions = res.permissions;
					} else {
						this.setRoutes = ['ROLE_DEFAULT'];
					}
					this.roles.push(user.userName);

					// 判断当前用户是否是管理员
					this.queryAdmin();

					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 判断当前用户是否是管理员
		queryAdmin() {
			return new Promise((resolve, reject) => {
				queryAdminApi().then(res => {
					this.isAdmin = res||false;
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 退出系统
		logOut() {
			return new Promise((resolve, reject) => {
				logout(this.token).then(res => {
					this.token = ''
					this.roles = []
					this.permissions = []
					removeToken()
					removeUserId()
					localStorage.removeItem("userName");
					localStorage.removeItem("orgName");
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		}
	}
})

export default useUserStore
